package com.jnu.keepaccounts;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.jnu.keepaccounts.data.Data;
import com.jnu.keepaccounts.data.DataBank;
import com.jnu.keepaccounts.data.DataForAnaylist;
import com.jnu.keepaccounts.data.DataTiaoMu;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.List;

public class Anaylist extends AppCompatActivity {
    private int[] colors = {R.color.purple_200,R.color.teal_200,
            R.color.red,R.color.a,
            R.color.b,R.color.c,
            R.color.d,R.color.e,
            R.color.f,R.color.g,
            R.color.h,R.color.i,
            R.color.j,R.color.k,
            R.color.l,R.color.blue
    };
    private BarChart barChart1,barChart2;
    private PieChart pieChart1,pieChart2;
    final int[] month = new int[3];
    final int[] year = new int[3];
    final int[] day = new int[3];
    private int flag = 0,flag1 = 0,flag2 = 1;
    private double shouru ,zhichu;
    private int numofshouru,numofzhichu,numofday;
    private Button[] buttons = new Button[8];
    private ArrayList<DataTiaoMu> datas = new ArrayList<>();
    private ArrayList<DataForAnaylist> finaldatasshou = new ArrayList<>();
    private ArrayList<DataForAnaylist> finaldataszhi = new ArrayList<>();
    private RecyclerView recyclerView,recyclerView1;
    private DataBank dataBank ;
    ArrayList<String> name_arrayList = new ArrayList<>();
    private AnaylistAdapter anaylistAdapter,anaylistAdapter1;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.anaylist);

        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }
        Calendar calendar = Calendar.getInstance();

        Intent intent = getIntent();
        month[2]  = calendar.get(Calendar.MONTH) + 1;
        year[2]  =  calendar.get(Calendar.YEAR);
        day[2]  = calendar.get(Calendar.DAY_OF_MONTH);
        if(intent.getIntExtra("year",0) != 0){
            month[0] = month[1] = intent.getIntExtra("month",0);
            year[0] = year[1] = intent.getIntExtra("year",0);
            day[0] = day[1] = intent.getIntExtra("day",0);
        }
        else {
            month[0] = month[1] = month[2];
            year[0] = year[1] = year[2];
            day[0] = day[1] = day[2];
        }
        recyclerView = findViewById(R.id.recyclerView_zhichu);
        recyclerView1 = findViewById(R.id.recyclerView_shouru);

        anaylistAdapter = new AnaylistAdapter(finaldataszhi);
        anaylistAdapter1 = new AnaylistAdapter(finaldatasshou);

        Integer[] one = new Integer[]{1,3,5,7,8,10,12};

        List<Integer> list = Arrays.asList(one);

        dataBank = new DataBank(getApplicationContext());

        Button button_next = findViewById(R.id.next);
        Button button_last = findViewById(R.id.last);

        button_last.setText(year[0]+"-"+month[0]+"-"+day[0]);
        button_next.setText(year[1]+"-"+month[1]+"-"+day[1]);

        numofday = 1;

        Button button_fenlei = findViewById(R.id.button_fenlei);
        Button button_account = findViewById(R.id.button_account);

        button_fenlei.setTextColor(Color.BLACK);
        button_account.setTextColor(Color.rgb(105,105,105));

        button_account.setOnClickListener(v -> {
            flag = 1;
            button_fenlei.setTextColor(Color.rgb(105,105,105));
            button_account.setTextColor(Color.BLACK);
            refresh(-1);
        });
        button_fenlei.setOnClickListener(v -> {
            flag = 0;
            button_fenlei.setTextColor(Color.BLACK);
            button_account.setTextColor(Color.rgb(105,105,105));
            refresh(-1);
        });

        ImageButton back = findViewById(R.id.back);
        Button all = findViewById(R.id.all);
        Button in = findViewById(R.id.in);
        Button out = findViewById(R.id.out);
        all.setTextColor(Color.BLACK);
        in.setTextColor(Color.rgb(105,105,105));
        out.setTextColor(Color.rgb(105,105,105));
        all.setOnClickListener(v -> {
            flag1 = 0;
            all.setTextColor(Color.BLACK);
            in.setTextColor(Color.rgb(105,105,105));
            out.setTextColor(Color.rgb(105,105,105));
            refresh(-1);
        });

        in.setOnClickListener(v -> {
            flag1 = -1;//预算内
            all.setTextColor(Color.rgb(105,105,105));
            in.setTextColor(Color.BLACK);
            out.setTextColor(Color.rgb(105,105,105));
            refresh(-1);
        });

        out.setOnClickListener(v -> {
            flag1 = 1;//预算外
            all.setTextColor(Color.rgb(105,105,105));
            in.setTextColor(Color.rgb(105,105,105));
            out.setTextColor(Color.BLACK);
            refresh(-1);
        });

        Button button_self = findViewById(R.id.button_self);
        Button button_this_month = findViewById(R.id.button_this_month);
        Button button_last_month = findViewById(R.id.button_last_month);
        Button button_near_three_months = findViewById(R.id.button_near_three_months);
        Button button_near_six_months = findViewById(R.id.button_near_six_months);
        Button button_this_year = findViewById(R.id.button_this_year);
        Button button_last_year = findViewById(R.id.button_last_year);
        Button button_so_far = findViewById(R.id.button_so_far);
        buttons[0] = button_self;
        buttons[1] = button_last_month;
        buttons[2] = button_near_three_months;
        buttons[3] = button_near_six_months;
        buttons[4] = button_this_year;
        buttons[5] = button_last_year;
        buttons[6] = button_so_far;
        buttons[7] = button_this_month;
        refresh(0);

        back.setOnClickListener(v -> finish());
        button_self.setOnClickListener(v -> {
            setButton(0);
        });
        button_this_month.setOnClickListener(v -> {
            year[0]= year[1] = year[2];
            month[0]= month[1] = month[2];
            day[0] = 1;
            if(month[1] == 2 ){
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                if(gregorianCalendar.isLeapYear(year[1])){
                    day[1] = 29 ;
                }
                else day[1] = 28;
            }
            else if(list.contains(month[1])){
                day[1] = 31;
            }
            else month[1] = 30;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(7);
        });
        button_last_month.setOnClickListener(v ->{

            if(month[2]-1>0){
                month[0] = month[1] = month[2]-1;
                year[0] = year[1] = year[2];
            }
            else {
                month[0] = month[1] = 12;
                year[0] = year[1] = year[2] - 1;
            }
            day[0] = 1;
            if(month[1] == 2 ){
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                if(gregorianCalendar.isLeapYear(year[1])){
                    day[1] = 29 ;
                }
                else day[1] = 28;
            }
            else if(list.contains(month[1])){
                day[1] = 31;
            }
            else day[1] = 30;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(1);
        });
        button_near_three_months.setOnClickListener(v -> {
            if(month[2]-2>0){
                month[0] = month[2]-2;
                month[1] = month[2];
                year[0] = year[1] = year[2];
            }
            else {
                month[0] = month[2]+10;
                year[1] = year[2];
                year[0] = year[2] - 1;
            }
            day[0] = 1;
            if(month[1] == 2 ){
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                if(gregorianCalendar.isLeapYear(year[1])){
                    day[1] = 29 ;
                }
                else day[1] = 28;
            }
            else if(list.contains(month[1])){
                day[1] = 31;
            }
            else day[1] = 30;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(2);
        });
        button_near_six_months.setOnClickListener(v -> {//近六个月

            if(month[2]-5>0){
                month[0] = month[2]-5;
            }
            else {
                month[0] = month[2]+7;
                year[0] = year[2] - 1;
            }
            month[1] = month[2];
            day[0] = 1;
            if(month[1] == 2 ){
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                if(gregorianCalendar.isLeapYear(year[1])){
                    day[1] = 29 ;
                }
                else day[1] = 28;
            }
            else if(list.contains(month[1])){
                day[1] = 31;
            }
            else month[1] = 30;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(3);
        });
        button_this_year.setOnClickListener(v -> {//本年
            year[0] = year[1] = year[2];
            month[0] = 1;
            month[1] = 12;
            day[0] = 1  ;
            day[1] = 31;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(4);
        });
        button_last_year.setOnClickListener(v -> {//去年
            year[0] = year[1] = year[2] - 1;
            month[0] = 1;
            month[1] = 12;
            day[0] = 1  ;
            day[1] = 31;
            button_last.setText(year[0] +"-"+month[0]+"-"+day[0]);
            button_next.setText(year[1] +"-"+month[1]+"-"+day[1]);
            refresh(5);
        });
        button_so_far.setOnClickListener(v -> {//迄今为止
            if(datas.size()!= 0){
                button_last.setText(datas.get(datas.size()-1).getYear()+"-"+datas.get(datas.size()-1).getMonth()+"-"+datas.get(datas.size()-1).getDay());
                button_next.setText(datas.get(0).getYear()+"-"+datas.get(0).getMonth()+"-"+datas.get(0).getDay());
                year[0] = datas.get(datas.size()-1).getYear();
                year[1] = datas.get(0).getYear();
                month[0] = datas.get(datas.size()-1).getMonth();
                month[1] = datas.get(0).getMonth();
                day[0] = datas.get(datas.size()-1).getDay();
                day[1] = datas.get(0).getDay();
            }
            refresh(6);
        });

        //时间选择
        button_last.setOnClickListener(v -> {
            //通过自定义控件AlertDialog实现
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            @SuppressLint("ResourceType") View view1 = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
            final DatePicker datePicker = (DatePicker) view1.findViewById(R.id.date_picker);
            //设置日期简略显示 否则详细显示 包括:星期\周
            datePicker.setCalendarViewShown(false);
            //设置date布局
            builder.setView(view1);
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //日期格式
                    year[0] = datePicker.getYear();
                    month[0] = datePicker.getMonth()+1;
                    day[0] = datePicker.getDayOfMonth();
                    button_last.setText(year[0] +"-"+ month[0] +"-"+ day[0]);
                    dialog.cancel();
                    refresh(0);
                }
            });
            builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
        });

        button_next.setOnClickListener(v -> {
            //通过自定义控件AlertDialog实现
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            @SuppressLint("ResourceType") View view1 = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
            final DatePicker datePicker = (DatePicker) view1.findViewById(R.id.date_picker);
            //设置日期简略显示 否则详细显示 包括:星期\周
            datePicker.setCalendarViewShown(false);
            //设置date布局
            builder.setView(view1);
            builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //日期格式
                    year[1] = datePicker.getYear();
                    month[1] = datePicker.getMonth()+1;
                    day[1] = datePicker.getDayOfMonth();
                    button_next.setText(year[1] +"-"+ month[1] +"-"+ day[1]);
                    dialog.cancel();
                    refresh(0);

                }
            });
            builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(layoutManager);
        recyclerView1.setLayoutManager(layoutManager1);

        recyclerView.setAdapter(anaylistAdapter);
        recyclerView1.setAdapter(anaylistAdapter1);

//        initBarChart();
    }

    private void initBarChart() {
        barChart1 = findViewById(R.id.bar_chart1);
        barChart2 = findViewById(R.id.bar_chart2);
        barChart1.clear();
        barChart2.clear();
        barChart1.getDescription().setEnabled(false);//不显示描述
        barChart2.getDescription().setEnabled(false);//不显示描述
        barChart1.setExtraOffsets(10,10,10,10);
        barChart2.setExtraOffsets(10,10,10,10);
        setAxis();
//        setLegend();
        setTuData();
    }
    private void initPieChart() {
        pieChart1 = findViewById(R.id.pie_chart1);
        pieChart2 = findViewById(R.id.pie_chart2);
        pieChart1.clear();
        pieChart2.clear();
        pieChart1.getDescription().setEnabled(false); // 不显示描述
        pieChart1.setDrawHoleEnabled(true);// 不显示饼图中间的空洞
        pieChart1.setDrawCenterText(true);
        pieChart1.setRotationEnabled(true); // 不允许饼图旋转
        pieChart1.setDrawEntryLabels(false); // 不在饼图中显示标签
        pieChart1.setExtraOffsets(5, 5, 5, 5); // 设置饼图的偏移量，类似于内边距 ，设置视图窗口大小

        pieChart2.getDescription().setEnabled(false); // 不显示描述
        pieChart2.setDrawHoleEnabled(true); // 不显示饼图中间的空洞
        pieChart2.setDrawCenterText(true);
        pieChart2.setRotationEnabled(true); // 不允许饼图旋转
        pieChart2.setDrawEntryLabels(false); // 不在饼图中显示标签
        pieChart2.setExtraOffsets(5, 5, 5, 5); // 设置饼图的偏移量，类似于内边距 ，设置视图窗口大小
        setPieData(); // 为饼图设置数据
    }

    private void setPieData() {
        MyMarkerView myMarkerView1,myMarkerView2;
        myMarkerView1 = new MyMarkerView(this,R.layout.marker);
        myMarkerView2 = new MyMarkerView(this,R.layout.marker);

        List<PieEntry> pieEntries1 = new ArrayList<>();
        List<PieEntry> pieEntries2 = new ArrayList<>();

        for(int i = 0;i<finaldataszhi.size();i++){
            pieEntries1.add(new PieEntry((float) finaldataszhi.get(i).getBnum(),finaldataszhi.get(i).getNameOrLaiYuan(),finaldataszhi.get(i)));
        }
        PieDataSet pieDataSet1 = new PieDataSet(pieEntries1,"");
        pieDataSet1.setColors(colors,getApplicationContext());


        PieData pieData1 = new PieData(pieDataSet1);
        pieData1.setDrawValues(false);
        pieChart1.setCenterText("支出\n"+zhichu);
        pieChart1.setCenterTextSize(15);
        pieChart1.setData(pieData1  );
        pieChart1.getLegend().setEnabled(false);
        pieChart1.setMarker(myMarkerView1);
        myMarkerView1.setChartView(pieChart1);



        for(int i = 0;i<finaldatasshou.size();i++){
            pieEntries2.add(new PieEntry((float) finaldatasshou.get(i).getBnum(),finaldatasshou.get(i).getNameOrLaiYuan(),finaldatasshou.get(i)));
        }
        PieDataSet pieDataSet2 = new PieDataSet(pieEntries2,"");
        pieDataSet2.setColors(colors,getApplicationContext());

        PieData pieData2 = new PieData(pieDataSet2);
        pieData2.setDrawValues(false);
        pieChart2.setMarker(myMarkerView2);
        myMarkerView2.setChartView(pieChart2);
        pieChart2.setCenterText("收入\n"+shouru);
        pieChart2.getLegend().setEnabled(false);
        pieChart2.setData(pieData2);
    }

    private void setTuData() {
//        List<IBarDataSet> sets1 = new ArrayList<>();

        MyMarkerView myMarkerView1,myMarkerView2;
        myMarkerView1 = new MyMarkerView(this,R.layout.marker);
        myMarkerView2 = new MyMarkerView(this,R.layout.marker);

        List<BarEntry> barEntries1 = new ArrayList<>();
        for(int i = 0;i<finaldataszhi.size();i++){
            barEntries1.add(new BarEntry(i, (float) finaldataszhi.get(i).getNum(),finaldataszhi.get(i)));
        }
        BarDataSet barDataSet1 = new BarDataSet(barEntries1,"");
        barDataSet1.setValueTextColor(Color.RED);
        barDataSet1.setValueTextSize(10f);
        barDataSet1.setColors(colors, getApplicationContext());

        BarData barData1 = new BarData(barDataSet1);
        barChart1.getLegend().setEnabled(false);
        barChart1.animateY(1000);
        barChart1.setMarker(myMarkerView1);
        myMarkerView1.setChartView(barChart1);
        barChart1.setData(barData1);

        List<BarEntry> barEntries2 = new ArrayList<>();
        for(int i = 0;i<finaldatasshou.size();i++){
            barEntries2.add(new BarEntry(i, (float) finaldatasshou.get(i).getNum(),finaldatasshou.get(i)));
        }
        BarDataSet barDataSet2 = new BarDataSet(barEntries2,"");
        barDataSet2.setValueTextColor(Color.RED);
        barDataSet2.setValueTextSize(10f);
        barDataSet2.setColors(colors,getApplicationContext());

        BarData barData2 = new BarData(barDataSet2);
        barChart2.getLegend().setEnabled(false);
        barChart2.animateY(1000);
        barChart2.setMarker(myMarkerView2);
        myMarkerView2.setChartView(barChart2);
        barChart2.setData(barData2);
    }

    private void setAxis() {
        if(finaldatasshou.size()>0){
            setAxisShou();
        }
        if(finaldataszhi.size()>0){
            setAxisZhi();
        }
    }

    private void setAxisZhi(){
        XAxis xAxis1 = barChart1.getXAxis();

        xAxis1.setPosition(XAxis.XAxisPosition.BOTTOM);

        xAxis1.setLabelCount(finaldataszhi.size());
        xAxis1.setEnabled(false);



        YAxis yAxis_left1 = barChart1.getAxisLeft();
        barChart1.getAxisRight().setEnabled(false);


        yAxis_left1.setAxisMaximum((float) Math.ceil(finaldataszhi.get(0).getNum()));

        yAxis_left1.setAxisMinimum(0f);


        yAxis_left1.setEnabled(false);

    }
    private void setAxisShou(){

        XAxis xAxis2 = barChart2.getXAxis();

        xAxis2.setPosition(XAxis.XAxisPosition.BOTTOM);

        xAxis2.setLabelCount(finaldatasshou.size());

        xAxis2.setEnabled(false);


        YAxis yAxis_left2 = barChart2.getAxisLeft();

        barChart2.getAxisRight().setEnabled(false);


        yAxis_left2.setAxisMaximum((float) Math.ceil(finaldatasshou.get(0).getNum()));

        yAxis_left2.setAxisMinimum(0f);

        yAxis_left2.setEnabled(false);
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void refresh(int flag ){
        setButton(flag);
        setData();
        setAver();
        initBarChart();
        initPieChart();

        anaylistAdapter.notifyDataSetChanged();
        anaylistAdapter1.notifyDataSetChanged();
    }
    public void setButton(int flag){//设置button字体颜色
        if(flag == -1)return ;
        for(int i = 0;i<8;i++){
            if( i == flag){
                buttons[i].setTextColor(Color.BLACK);
            }
            else buttons[i].setTextColor(Color.rgb(128,128,128));
        }
    }
    public void setAver(){
        TextView textView = findViewById(R.id.text_tongjiqingkuang);
        textView.setText("支出："+zhichu+"，收入："+shouru+"，结余："+(shouru-zhichu));
        TextView textView1 = findViewById(R.id.text_zhichutongjiqingkuang);
        TextView textView2 = findViewById(R.id.text_shourutongjiqingkuang);
        if(numofzhichu == 0){
            textView1.setText("支出平均每日：0.00，平均每笔：0.00");
        }
        else{
            int tem = (int) ((zhichu/numofday)*100);
            int tem1 = (int) ((zhichu/numofzhichu)*100);
            textView1.setText("支出平均每日："+tem/100.0+"，平均每笔："+tem1/100.0);
        }
        if(numofshouru == 0 ){
            textView2.setText("收入平均每日：0.00，平均每笔：0.00");
        }
        else{
            int tem = (int) ((shouru/numofday)*100);
            int tem1 = (int) ((shouru/numofshouru)*100);
            textView2.setText("收入平均每日："+tem/100.0+"，平均每笔："+tem1/100.0);
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setData(){
        dataBank = new DataBank(getApplicationContext());

        Calendar calendar = Calendar.getInstance();
        calendar.set(year[0],month[0],day[0]);
        Long last = calendar.getTimeInMillis();
        calendar.set(year[1],month[1],day[1]);
        Long next = calendar.getTimeInMillis();
        numofday = (int) ((next - last)/86400000)+1;
        Long tem;
        datas.clear();
        name_arrayList.clear();
        finaldatasshou.clear();
        finaldataszhi.clear();
        for(Data data:dataBank.loadData()){
            if(data.getFlag() == 1){
                calendar.set(data.getYear(),data.getMonth(),data.getDay());
                tem = calendar.getTimeInMillis();
                if(((DataTiaoMu) data).getYusuan() == flag1 || flag1 == 0){
                    if(tem>=last&&tem<=next) {
                        String name;
                        if(this.flag == 0){
                            name = ((DataTiaoMu) data).getXiangMu();
                            if (!name_arrayList.contains(name)) {
                                name_arrayList.add(name);
                                finaldatasshou.add(new DataForAnaylist(((DataTiaoMu) data).getXiangMu(),((DataTiaoMu) data).getImage(),0,0));
                                finaldataszhi.add(new DataForAnaylist(((DataTiaoMu) data).getXiangMu(),((DataTiaoMu) data).getImage(),0,0));
                            }
                        }
                        else {
                            name = ((DataTiaoMu) data).getLaiYuan();
                            if (!name_arrayList.contains(name)) {
                                name_arrayList.add(name);
                                finaldatasshou.add(new DataForAnaylist(((DataTiaoMu) data).getLaiYuan(),0,0,0));
                                finaldataszhi.add(new DataForAnaylist(((DataTiaoMu) data).getLaiYuan(),0,0,0));
                            }
                        }
                        datas.add((DataTiaoMu) data);
                    }
                }
            }
        }
        Tongji();
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void Tongji(){
        int flag = name_arrayList.size();
        double[] shou = new double[flag];
        double[] zhi = new double[flag];
        shouru = zhichu = numofshouru = numofzhichu = 0;
        for(DataTiaoMu dataTiaoMu:datas){
            double tem = dataTiaoMu.getShuE();
            String name;
            if(this.flag == 0){
                name = dataTiaoMu.getXiangMu();
            }
            else {
                name = dataTiaoMu.getLaiYuan();
            }
//            int i = 0;
//            int bbb = name_arrayList.indexOf(dataTiaoMu.getXiangMu());
//            for(;i<flag;i++){
//                if(dataTiaoMu.getXiangMu().equals(name_arrayList.get(i)))break;
//            }
            if(tem > 0){
                shou[name_arrayList.indexOf(name)] += tem;
                shouru += tem;
                numofshouru += 1;
            }
            else {
                zhi[name_arrayList.indexOf(name)] -= tem;
                zhichu -= tem;
                numofzhichu += 1;
            }
        }

        for(int i = 0;i<flag ;i++){
            int num;
            if(shouru!=0){
                num = (int) (shou[i]/shouru*10000);
                finaldatasshou.get(i).setNum(shou[i]);
                finaldatasshou.get(i).setBnum(num/100.0);
            }
            if(zhichu!=0){
                num = (int) (zhi[i]/zhichu*10000);
                finaldataszhi.get(i).setNum(zhi[i]);
                finaldataszhi.get(i).setBnum(num/100.0);
            }
        }
        finaldataszhi.sort((e1,e2)->{
            if(e1.getNum()<e2.getNum())return 1;
            else return -1;
        });
        finaldatasshou.sort((e1,e2)->{
            if(e1.getNum()<e2.getNum())return 1;
            else return -1;
        });
        int i,zero = 0;
        for(i = 0;i<flag ;i++){
            if(finaldatasshou.get(i).getNum() == 0){zero = i;break;}
        }
        for(;i<flag;i++){
            finaldatasshou.remove(zero);
        }

        for(i = 0;i<flag;i++){
            if(finaldataszhi.get(i).getNum() == 0){zero = i;break;}
        }
        for (;i<flag;i++){
            finaldataszhi.remove(zero);
        }
    }

    @SuppressLint("WrongConstant")
    public void onClick(View view) {
        flag2 = -flag2;
        if(flag2 == 1){
            barChart1.setVisibility(8);
            barChart2.setVisibility(8);
            pieChart1.setVisibility(0);
            pieChart2.setVisibility(0);
        }
        else {
            barChart1.setVisibility(0);
            barChart2.setVisibility(0);
            pieChart1.setVisibility(8);
            pieChart2.setVisibility(8);
        }
    }

    public class AnaylistAdapter extends RecyclerView.Adapter<AnaylistAdapter.ViewHolder>{
        private ArrayList<DataForAnaylist> dataForAnaylists;
        AnaylistAdapter(ArrayList<DataForAnaylist> dataForAnaylists){
            this.dataForAnaylists = dataForAnaylists;
        }
        @NonNull
        @Override
        public AnaylistAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new AnaylistAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.anaylistviewholder,parent,false));
        }

        @SuppressLint("WrongConstant")
        @Override
        public void onBindViewHolder(@NonNull AnaylistAdapter.ViewHolder holder, int position) {
            DataForAnaylist data = dataForAnaylists.get(position);
            if(data.getPictureId() == 0){
                holder.imageView.setVisibility(8);
            }
            else{
                holder.imageView.setVisibility(0);
                holder.imageView.setImageResource(data.getPictureId());
            }
            holder.anaylist_name.setText(data.getNameOrLaiYuan());
            holder.anaylist_baifenbi.setText(data.getBnum()+"%");
            holder.anaylist_total.setText(data.getNum()+"");
        }

        @Override
        public int getItemCount() {
            return dataForAnaylists.size();
        }
        public class ViewHolder extends RecyclerView.ViewHolder{
            ImageView imageView ;
            TextView anaylist_name;
            TextView anaylist_baifenbi;
            TextView anaylist_total;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.anaylist_image);
                anaylist_name = itemView.findViewById(R.id.anaylist_name);
                anaylist_baifenbi = itemView.findViewById(R.id.anaylist_baifenbi);
                anaylist_total = itemView.findViewById(R.id.anaylist_total);
            }
        }
    }
}
